package com.fecean.aabbc.netty.handler7;

import com.fecean.aabbc.netty.message7.MessageBuilder;
import com.fecean.aabbc.netty.message7.MessageType;
import com.fecean.aabbc.netty.message7.RequestMessage;
import com.fecean.aabbc.netty.message7.ResponseMessage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 ** 请求通道处理
 *
 * @author: chenfenghai
 * @version: 1.0
 * @date: 2020-03-05 15:59
 * @blame Team
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class NettyRequestChannelHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    private ApplicationContext context;

    /**
     ** 读取数据处理
     *
     * @param ctx 通道上下文
     * @param msg 读取到的数据
     * @throws Exception 处理过程中存在异常则抛出
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        MessageBuilder requestBuilder = MessageBuilder.of(msg);
        if(requestBuilder.isMessage(MessageType.REQUEST)){
            log.info("客户端[{}-{}]收到请求：{}", requestBuilder.getMessage().getTenantId(),
                    requestBuilder.getMessage().getCinemaCode(), requestBuilder.getMessage());

            // 执行请求服务，并返回响应结果
            ResponseMessage message = executeRequestService((RequestMessage) requestBuilder.getMessage());
            ctx.writeAndFlush(message.toDataObject());
            return;
        }
        ctx.fireChannelRead(msg);
    }

    /**
     ** 执行请求服务，并返回响应结果
     *
     * @param requestMessage 请求消息
     * @return 响应结果
     */
    private ResponseMessage executeRequestService(RequestMessage requestMessage){
        ResponseMessage responseMessage = MessageBuilder.buildResponseMessage(
                requestMessage.getId(),
                requestMessage.getTenantId(),
                requestMessage.getCinemaCode(),
                "{\"result\":\"响应结果\"}");

//        ResponseMessage responseMessage = ResponseMessage.builder()
//                .id(requestMessage.getId())
//                .tenantId(requestMessage.getTenantId())
//                .cinemaCode(requestMessage.getCinemaCode())
//                .timestamp(Instant.now().toEpochMilli())
//                .build();
//        try {
//            IceRequest request = new IceRequest(requestMessage.getContent());
//            IceResponse response = new IceResponse(request.getCmd(), request.getUuid());
//            Object bean = context.getBean(requestMessage.getServiceName());
//            Method method = ReflectionUtils.findMethod(bean.getClass(), requestMessage.getMethodName(), IceRequest.class, IceResponse.class);
//            if(method == null){
//                throw new RuntimeException("找不到方法：" + requestMessage.getServiceName() + "." + requestMessage.getMethodName());
//            }
//            ReflectionUtils.invokeMethod(method, bean, request, response);
//            responseMessage.setContent(response.toJson());
//        }catch (Exception ex){
//            log.error("", ex);
//            responseMessage.setContent(ex.getMessage());
//        }
        log.info("客户端[{}-{}]响应结果：{}",
                responseMessage.getTenantId(), responseMessage.getCinemaCode(), responseMessage);
        return responseMessage;
    }
}
